package com.shenhan.pc;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author shenhan
 * @create 2020/6/10 14:30
 * @description juc版生产者消费者
 */
public class B {
    public static void main(String[] args) {
        Data2 data = new Data2();
        new Thread(() -> {for (int i = 0; i < 10; i++) {data.increment();}}, "A").start();
        new Thread(() -> {for (int i = 0; i < 10; i++) {data.decrement();}}, "B").start();
        new Thread(() -> {for (int i = 0; i < 10; i++) {data.increment();}}, "C").start();
        new Thread(() -> {for (int i = 0; i < 10; i++) {data.decrement();}}, "D").start();
    }
}

class Data2 {
    private int number = 0;
    final Lock lock = new ReentrantLock();
    private final Condition condition = lock.newCondition();

    public void increment() {
        lock.lock();
        try {
            while (number != 0) {
                condition.await();
            }
            number++;
            System.out.println(Thread.currentThread().getName() + " => " + number);
            condition.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void decrement() {
        lock.lock();
        try {
            while (number == 0) {
                condition.await();
            }
            number--;
            System.out.println(Thread.currentThread().getName() + " => " + number);
            condition.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}
